<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
        <Head :singleAdd="singleAdd" />
        <Body
          :todoList="todoList"
          :singleChange="singleChange"
          :singleDelete="singleDelete"
        />
        <Footer
          :todoList="todoList"
          :allChange="allChange"
          :allClear="allClear"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { nanoid } from 'nanoid'
import Head from '../../components/TodoList/Header'
import Body from '../../components/TodoList/Body'
import Footer from '../../components/TodoList/Footer'
export default {
  // todolist实现数据的持久化存储
  data() {
    return {
      // 当加载时获取存储在浏览器中的数据然后加载到vm组件实例中去
      todoList: JSON.parse(localStorage.getItem('todoList')) || [],
      // [
      //   { id: nanoid(), thing: '唱', done: false },
      //   { id: nanoid(), thing: '跳', done: false },
      //   { id: nanoid(), thing: 'rap', done: false },
      // ]
    }
  },
  watch: {
    todoList: {
      deep: true,
      immediate: true,
      handler(newVal) {
        // 当数据改变时触发watch改变,更新在localStorage中的值,并且更新页面中存储的离线值,更新整个页面
        localStorage.setItem('todoList', JSON.stringify(newVal))
      },
    },
  },
  methods: {
    singleChange(id) {
      this.todoList.forEach((element) => {
        if (element.id === id) {
          element.done = !element.done
        }
      })
    },
    singleDelete(id) {
      // 使用filter过滤删除
      let newTodo = this.todoList.filter((item) => item.id != id)
      this.todoList = newTodo
    },
    singleAdd(value) {
      console.log(value)
      this.todoList.unshift({
        id: nanoid(),
        thing: value,
        done: false,
      })
    },
    allChange(done) {
      this.todoList.forEach((item) => {
        item.done = done
      })
    },
    allClear() {
      let newTolist = this.todoList.filter((item) => !item.done)
      this.todoList = newTolist
    },
  },
  components: {
    Head,
    Body,
    Footer,
  },
}
</script>

<style>
/*base*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
    0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
